package com.ml4ai.core.json

import com.google.gson.{Gson, JsonParser}

class StringJsonWrapper(val json: String) {

  val element = new JsonParser().parse(json)

  def addString(key: String, value: String): String = {
    val obj = element.getAsJsonObject
    obj.addProperty(key, value)
    new Gson().toJson(obj)
  }

  def addString(value: String): String = {
    val obj = element.getAsJsonArray
    obj.add(value)
    new Gson().toJson(obj)
  }

  def addNumber(key: String, value: Number): String = {
    val obj = element.getAsJsonObject
    obj.addProperty(key, value)
    new Gson().toJson(obj)
  }

  def addNumber(value: Number): String = {
    val obj = element.getAsJsonArray
    obj.add(value)
    new Gson().toJson(obj)
  }

  def addJson(key: String, value: String): String = {
    val obj = element.getAsJsonObject
    obj.add(key, new JsonParser().parse(value))
    new Gson().toJson(obj)
  }

  def addJson(value: String): String = {
    val obj = element.getAsJsonArray
    obj.add(new JsonParser().parse(value))
    new Gson().toJson(obj)
  }

  def get(key: String): String = {
    val jsonObject = element.getAsJsonObject
    val el = jsonObject.get(key)
    if (el == null || el.isJsonNull)
      null
    else if (el.isJsonPrimitive)
      el.getAsString
    else if (el.isJsonObject)
      el.getAsJsonObject.toString
    else
      el.getAsJsonArray.toString
  }

  def get(ind: Int): String = {
    val jsonArray = element.getAsJsonArray
    val el = jsonArray.get(ind)
    if (el == null || el.isJsonNull)
      null
    else if (el.isJsonPrimitive)
      el.getAsString
    else if (el.isJsonObject)
      el.getAsJsonObject.toString
    else
      el.getAsJsonArray.toString
  }

}

object stringJson {
  implicit def string2json(value: String): StringJsonWrapper = {
    new StringJsonWrapper(value)
  }
}